namespace BM.Tools.WebControls.MForm.Navigation.XPath
{
    using System;

    using BM.Tools.WebControls.MForm.Navigation.XPath.Predicates;    

    /// <summary>
    /// A definition of the xpath predicate
    /// </summary>
    public abstract class Predicate
    {
        /// <summary>
        /// Creates the predicate object from its string representatino
        /// </summary>
        /// <param name="predicateText">
        /// The predicate text.
        /// </param>
        /// <returns>
        /// the appropriate predicate
        /// </returns>
        public static Predicate Create(string predicateText)
        {
            if (string.IsNullOrEmpty(predicateText))
            {
                return null;
            }

            predicateText = predicateText.Trim();
            int result;
            if (predicateText.StartsWith("not(", StringComparison.Ordinal))
            {
                return new NegationPredicate(Create(predicateText.Substring(4, predicateText.Length - 5)));
            }

            if (predicateText.Contains(" or "))
            {
                return new AlternativesPredicate(predicateText.Split(new[] { " or " }, StringSplitOptions.None));
            }

            if (predicateText.Contains(" and "))
            {
                return new ConjunctionPredicate(predicateText.Split(new[] { " and " }, StringSplitOptions.None));
            }

            if (int.TryParse(predicateText, out result))
            {
                return new PositionPredicate(result);
            }

            return new NamePredicate(predicateText);
        }
    }
}